import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:intl/intl.dart';
import '../viewmodels/task_view_model.dart';
import '../models/task_model.dart';

/// 添加/编辑任务屏幕
/// 用于创建新任务或编辑现有任务
class AddEditTaskScreen extends StatefulWidget {
  final String? taskId;

  const AddEditTaskScreen({super.key, this.taskId});

  @override
  State<AddEditTaskScreen> createState() => _AddEditTaskScreenState();
}

class _AddEditTaskScreenState extends State<AddEditTaskScreen> {
  final _formKey = GlobalKey<FormState>();
  late TextEditingController _nameController;
  late TextEditingController _notesController;
  DateTime? _startDate;
  DateTime? _endDate;
  bool _reminderEnabled = false;

  @override
  void initState() {
    super.initState();
    _nameController = TextEditingController();
    _notesController = TextEditingController();

    // 如果是编辑任务，则加载任务数据
    if (widget.taskId != null) {
      final taskViewModel = Provider.of<TaskViewModel>(context, listen: false);
      final task = taskViewModel.getTaskById(widget.taskId!);
      if (task != null) {
        _nameController.text = task.name;
        _notesController.text = task.notes;
        _startDate = task.startDate;
        _endDate = task.endDate;
        _reminderEnabled = task.reminderEnabled;
      }
    } else {
      // 设置默认日期为今天和7天后
      _startDate = DateTime.now();
      _endDate = DateTime.now().add(const Duration(days: 7));
    }
  }

  @override
  void dispose() {
    _nameController.dispose();
    _notesController.dispose();
    super.dispose();
  }

  Future<void> _selectStartDate(BuildContext context) async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: _startDate ?? DateTime.now(),
      firstDate: DateTime.now().subtract(const Duration(days: 365)),
      lastDate: DateTime.now().add(const Duration(days: 365)),
    );
    if (picked != null && picked != _startDate) {
      setState(() {
        _startDate = picked;
        // 如果结束日期早于开始日期，则更新结束日期
        if (_endDate != null && _endDate!.isBefore(_startDate!)) {
          _endDate = _startDate!.add(const Duration(days: 7));
        }
      });
    }
  }

  Future<void> _selectEndDate(BuildContext context) async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: _endDate ?? DateTime.now().add(const Duration(days: 7)),
      firstDate: _startDate ?? DateTime.now(),
      lastDate: DateTime.now().add(const Duration(days: 365)),
    );
    if (picked != null && picked != _endDate) {
      setState(() {
        _endDate = picked;
      });
    }
  }

  void _saveTask() {
    if (_formKey.currentState!.validate() && _startDate != null && _endDate != null) {
      _formKey.currentState!.save();

      final taskViewModel = Provider.of<TaskViewModel>(context, listen: false);
      final task = TaskModel(
        id: widget.taskId ?? DateTime.now().millisecondsSinceEpoch.toString(),
        name: _nameController.text,
        startDate: _startDate!,
        endDate: _endDate!,
        notes: _notesController.text,
        reminderEnabled: _reminderEnabled,
        updatedAt: DateTime.now(),
      );

      if (widget.taskId != null) {
        taskViewModel.updateTask(task);
      } else {
        taskViewModel.addTask(task);
      }

      Navigator.pop(context);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.taskId != null ? '编辑任务' : '添加任务'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                TextFormField(
                  controller: _nameController,
                  decoration: const InputDecoration(
                    labelText: '打卡名称',
                    border: OutlineInputBorder(),
                  ),
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return '请输入打卡名称';
                    }
                    return null;
                  },
                ),
                const SizedBox(height: 16.0),
                Row(
                  children: [
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children:
                        [
                          const Text('开始日期'),
                          ElevatedButton(
                            onPressed: () => _selectStartDate(context),
                            child: Text(
                              _startDate != null
                                  ? DateFormat('yyyy-MM-dd').format(_startDate!)
                                  : '选择开始日期',
                            ),
                          ),
                        ],
                      ),
                    ),
                    const SizedBox(width: 16.0),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children:
                        [
                          const Text('结束日期'),
                          ElevatedButton(
                            onPressed: () => _selectEndDate(context),
                            child: Text(
                              _endDate != null
                                  ? DateFormat('yyyy-MM-dd').format(_endDate!)
                                  : '选择结束日期',
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 16.0),
                TextFormField(
                  controller: _notesController,
                  decoration: const InputDecoration(
                    labelText: '备注',
                    border: OutlineInputBorder(),
                    // maxLines: 3,
                  ),
                ),
                const SizedBox(height: 16.0),
                CheckboxListTile(
                  title: const Text('启用消息提醒'),
                  value: _reminderEnabled,
                  onChanged: (value) {
                    setState(() {
                      _reminderEnabled = value ?? false;
                    });
                  },
                ),
                const SizedBox(height: 32.0),
                Center(
                  child: ElevatedButton(
                    onPressed: _saveTask,
                    style: ElevatedButton.styleFrom(
                      padding: const EdgeInsets.symmetric(horizontal: 32.0, vertical: 12.0),
                    ),
                    child: const Text('保存'),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}